package projectx.core.base;

import java.sql.Connection;

import javax.jms.QueueConnection;

import org.apache.log4j.Logger;

import projectx.db.ProjectXConnectionManager;

public class ThreadContext {

	private static Logger logger = Logger.getLogger(ThreadContext.class);

	private static final ThreadLocal CONN_HANDLER = new ThreadLocal();

	private static final ThreadLocal AUTH_HANDLER = new ThreadLocal();

	private static final ThreadLocal QUEUE_CONN_HANDLER = new ThreadLocal();

	private ThreadContext() {
		super();
	}

	public static final void setConnection() throws ProjectXSystemException {
		synchronized (CONN_HANDLER) {
			Connection conn = ProjectXConnectionManager.getConnection();
			CONN_HANDLER.set(conn);
		}
	}

	public static final Connection getNewConnection()
			throws ProjectXSystemException {
		return ProjectXConnectionManager.getConnection();
	}

	public static final Connection getConnection() {
		synchronized (CONN_HANDLER) {
			if (CONN_HANDLER.get() == null) {
				return null;
			}

			if (CONN_HANDLER.get() instanceof Connection) {
				return (Connection) CONN_HANDLER.get();
			}

			throw new IllegalArgumentException("Unknow Error["
					+ CONN_HANDLER.get().getClass().toString() + "] ["
					+ CONN_HANDLER.get().toString() + "]。");

		}
	}

	public static final void setCurrentAuth(final Object userId) {
		synchronized (AUTH_HANDLER) {
			AUTH_HANDLER.set(userId);
		}
	}

	public static final Object getCurrentAuth() {
		synchronized (AUTH_HANDLER) {
			if (AUTH_HANDLER.get() == null) {
				return null;
			}

			if (AUTH_HANDLER.get() instanceof String) {
				return AUTH_HANDLER.get();
			}

			throw new IllegalArgumentException("Unknow Error["
					+ AUTH_HANDLER.get().getClass().toString() + "] ["
					+ AUTH_HANDLER.get().toString() + "]。");
		}
	}

	public static final void setConnection(Connection conn)
			throws ProjectXSystemException {
		synchronized (CONN_HANDLER) {
			CONN_HANDLER.set(conn);
		}
	}

	public static final void setQueueConnection(QueueConnection queueConn)
			throws ProjectXSystemException {
		synchronized (QUEUE_CONN_HANDLER) {
			QUEUE_CONN_HANDLER.set(queueConn);
		}
	}

	public static final QueueConnection getQueueConnection()
			throws ProjectXSystemException {
		synchronized (QUEUE_CONN_HANDLER) {
			if (QUEUE_CONN_HANDLER.get() == null) {
				throw new ProjectXSystemException("E0000");
			}

			if (!(QUEUE_CONN_HANDLER.get() instanceof QueueConnection)) {
				throw new IllegalArgumentException("Unknow Error["
						+ QUEUE_CONN_HANDLER.get().getClass().toString()
						+ "] [" + QUEUE_CONN_HANDLER.get().toString() + "]。");
			}

			return (QueueConnection) QUEUE_CONN_HANDLER.get();
		}
	}
}
